<template>
  <div class="tenantMenu_main main_container">
    <div class="main_header">
      <div class="padding_container">
        <div class="left"><Breadcrumb /></div>
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="main_main">
      <search-bar-new :parent="this" />
      <div ref="table_container" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          row-key="orderByNumber"
          :cell-class-name="cellClassName"
          :cell-style="cellStyle"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          @cell-click="cellClick"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" width="70" align="center" />
          <Column v-for="(column,index) in tableColumns" :key="index" :prop="column.prop" :is-show="column.isShow" :label="column.label" :sortable="column.sortable" :width="column.width" :min-width="column.minWidth" />
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll.length"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import { exportList } from '@/api/qualityManage/customMadeStatement'
import { userList } from '@/api/system/dept'
import { list as materType } from '@/api/warehouseManagement/materialType'
import { getInfo as comeMaterialCheckoutInfo } from '@/api/qualityManage/comeMaterialCheckout'
import { getInfo as productionInspectionFormInfo } from '@/api/qualityManage/productionInspectionForm'
import ShowDetailOld from '@/views/qualityManage/comeMaterialCheckout/showQuality'
export default {
  name: 'Index',
  data() {
    return {
      loading: true,
      pageId: '质量报表',
      pageExportId: '质量报表导出',
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'code',
        isAsc: 'desc',
        onlyId: ''
      },
      total: 1, // 数据一共有多少条
      mainId: 'id',
      tableHeight: '0',
      tableData: [],
      tableData2: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'code', label: '检验单号', minWidth: '180' },
        { prop: 'formTypeName', label: '检验类型', minWidth: '140', canOrder: false, isRegular: true },
        { prop: 'checkName', label: '检验人员', minWidth: '140', canOrder: false, isRegular: true },
        { prop: 'checkDate', label: '检验日期', canOrder: false, isRegular: true },
        { prop: 'materialCode', label: '物料编码', minWidth: '180' },
        { prop: 'materialName', label: '物料名称', canOrder: false },
        { prop: 'materialModel', label: '规格型号', canOrder: false },
        { prop: 'materialTypeName', label: '物料分类', canOrder: false },
        { prop: 'materialUnitName', label: '物料单位', canOrder: false },
        { prop: 'purchaseInspectCode', label: '送检单号', minWidth: '180', canOrder: false },
        { prop: 'qualityTemplateName', label: '检验模板', canOrder: false },
        { prop: 'checkNumber', label: '送检数量', minWidth: this.SETTINGS.settings_decimalDigits_length, canOrder: false }
      ],
      defaultExport: [],
      exportTableColumns: [// 表格常规字段（初始值）
        { prop: 'code', label: '检验单号', minWidth: '140', isRegular: true },
        { prop: 'formTypeName', label: '检验类型', canOrder: false, isRegular: true },
        { prop: 'checkName', label: '检验人员', minWidth: '200', canOrder: false, isRegular: true },
        { prop: 'checkDate', label: '检验日期', isRegular: true },
        { prop: 'materialCode', label: '物料编码', canOrder: false, isRegular: true },
        { prop: 'materialName', label: '物料名称' },
        { prop: 'materialModel', label: '规格型号', canOrder: false },
        { prop: 'materialTypeName', label: '物料分类', canOrder: false },
        { prop: 'materialUnitName', label: '物料单位', canOrder: false },
        { prop: 'purchaseInspectCode', label: '送检单号', canOrder: false },
        { prop: 'qualityTemplateName', label: '检验模板', canOrder: false },
        { prop: 'checkNumber', label: '送检数量', minWidth: this.SETTINGS.settings_decimalDigits_length, canOrder: false }
      ],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'allSearchValue', label: '模糊搜索', type: 'input' },
        { prop: 'formType', label: '检验类型', type: 'select', optionsName: 'formTypeLabellList' },
        { prop: 'checkBy', label: '检验人员', type: 'select', optionsName: 'userList' },
        { prop: 'checkDate', label: '检验日期', type: 'time', isTime: true },
        { prop: 'materialType', label: '物料分类', type: 'select', optionsName: 'materialTypeList' }
      ],
      formTypeLabellList: [
        { label: '全部', value: undefined },
        { label: '采购检验', value: '1' },
        { label: '生产检验', value: '2' }
      ],
      userList: [],
      materialTypeList: [],
      operationData: [ // 右上角的操作按钮
        // { label: '新增', perm: '' },
        // { label: '批量删除', perm: '' },
        { label: '批量导出3', perm: '' },
        { label: '页面配置', perm: '' }
      ],
      showKey: {
        type: 'column_two',
        keys: [
          { type: 'form', name: '采购检验单号', key: 'code' },
          { type: 'form', name: '检验人员', key: 'checkName' },
          { type: 'form', name: '检验日期', key: 'checkDate' },
          { type: 'form', name: '物料编码', key: 'materialCode' },
          { type: 'form', name: '物料名称', key: 'materialName' },
          { type: 'form', name: '规格型号', key: 'materialModel' },
          { type: 'form', name: '物料单位', key: 'materialUnitName' },
          { type: 'form', name: '送检单号', key: 'purchaseInspectCode' },
          { type: 'form', name: '检验模板', key: 'qualityTemplateName' },
          { type: 'form', name: '送检数量', key: 'checkNumber' },
          { type: 'form', name: '抽检数量', key: 'spotCheckNumber' },
          { type: 'form', name: '不合格数量', key: 'disqualificationNumber' },
          { type: 'form', name: '合格数量', key: 'qualifiedNumber' },
          { type: 'form', name: '判定结果', key: 'resultCode' },
          { type: 'isInForm', name: '是否入库', key: 'isInForm' },
          { type: 'file', name: '附件', fileName: 'fileName', fileRealName: 'fileRealName', fileUrl: 'url' },
          { type: 'form', name: '不良描述', key: 'description', length: 'double' },
          { type: 'file', name: '检验图例', fileName: 'templateFileNames', fileRealName: 'templateFileRealNames', fileUrl: 'templateFileUrls' },
          {
            type: 'table1', name: '整体项目', key: 'data1', columns: [ // type: 'table' 表示是表格
              { name: '检验项目', key: 'qualityItemName', minWidth: '120' }
            ]
          },
          {
            type: 'table', name: '个体项目', key: 'data', columns: [ // type: 'table' 表示是表格
              { name: '检验项目', key: 'qualityItemName', minWidth: '120' }
            ]
          }
        ]
      },
      showKey1: {
        type: 'column_two',
        keys: [
          { type: 'form', name: '生产检验单号', key: 'code' },
          { type: 'form', name: '检验人员', key: 'checkByName' },
          { type: 'form', name: '检验时间', key: 'checkDate' },
          { type: 'form', name: '物料编码', key: 'materialCode' },
          { type: 'form', name: '物料名称', key: 'materialName' },
          { type: 'form', name: '规格型号', key: 'materialModel' },
          { type: 'form', name: '物料单位', key: 'materialUnitName' },
          { type: 'form', name: '关联任务单', key: 'productTaskCode' },
          { type: 'form', name: '工艺要求', key: 'engineeringRequirementCode' },
          { type: 'form', name: '工序', key: 'engineeringProcessName' },
          { type: 'form', name: '检验模板', key: 'qualityTemplateName' },
          { type: 'form', name: '送检数量', key: 'checkNumber' },
          { type: 'form', name: '抽检数量', key: 'spotCheckNumber' },
          { type: 'form', name: '不合格数量', key: 'disqualificationNumber' },
          { type: 'form', name: '合格数量', key: 'qualifiedNumber' },
          { type: 'form', name: '判定结果', key: 'resultCode' },
          { type: 'isInForm', name: '是否入库', key: 'isInForm' },
          { type: 'file', name: '附件', fileName: 'fileName', fileRealName: 'fileRealName', fileUrl: 'url' },
          { type: 'form', name: '不良描述', key: 'description', length: 'double' },
          { type: 'file', name: '检验图例', fileName: 'templateFileNames', fileRealName: 'templateFileRealNames', fileUrl: 'templateFileUrls' },
          {
            type: 'table1', name: '整体项目', key: 'data1', columns: [ // type: 'table' 表示是表格
              { name: '检验项目', key: 'qualityItemName', minWidth: '120' }
            ]
          },
          {
            type: 'table', name: '个体项目', key: 'data', columns: [ // type: 'table' 表示是表格
              { name: '检验项目', key: 'qualityItemName', minWidth: '120' }
            ]
          }
        ]
      },
      statusOptions: [],
      defaultSearchTime: [],
      statusOptionsWarehouse: []
    }
  },
  computed: {
    // 分页器
    selectedNum() {
      return this.$refs.table ? this.$refs.table.selection.length : 0
    }
  },
  // watch: {
  //   tableData() {
  //     this.$nextTick(() => {
  //       for (const elementNodeListOfElement of document.querySelectorAll('.SaleOrderCodeColumnClass')) {
  //         if (!elementNodeListOfElement.childNodes[0].childNodes[0].className || elementNodeListOfElement.childNodes[0].childNodes[0].className == 'commonTableColumn') {
  //           const paddingNode = document.createElement('div')
  //           paddingNode.className = 'SaleOrderCodeColumnClass_expand'
  //           paddingNode.innerHTML = ''
  //           elementNodeListOfElement.childNodes[0].insertBefore(paddingNode, elementNodeListOfElement.childNodes[0].childNodes[0])
  //         }
  //       }
  //     })
  //   }
  // },
  created() {
    this.getTypeList()
    this.getUser()
    // this.defaultSearchTime = [this.$moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD') + ' 00:00',
    //   this.$moment(new Date()).format('YYYY-MM-DD') + ' 23:59']
  },
  mounted() {
    setTimeout(() => {
      this.$forceUpdate()
      this.$refs.table.doLayout()
    }, 200)
  },
  methods: {
    cellStyle({ row, column }) {
      if (column.property == 'code') {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
    },
    cellClick(row, column, cell) {
      switch (column.property) {
        case 'code':
          this.examine(row)
          break
      }
    },
    examine(row) {
      if (row.formTypeName == '采购检验') {
        comeMaterialCheckoutInfo(row[this.mainId]).then(res => {
          const showData = this.$deepClone(res.data)
          if (showData.resultCode == 0) {
            showData.resultCode = '通过'
          } else if (showData.resultCode == 1) {
            showData.resultCode = '不通过'
          }
          const newlistData = JSON.parse(res.data.titleJson)
          const newlistData1 = JSON.parse(res.data.entityTitleJson)
          const newData = JSON.parse(res.data.qualityJson)
          const newData1 = JSON.parse(res.data.entityQualityJson)
          showData.listData = newlistData
          showData.listData1 = newlistData1
          showData.data = newData
          showData.data1 = newData1
          this.$layer.iframe({// 弹框
            content: {
              content: ShowDetailOld, // 传递的组件对象
              parent: this, // 当前的vue对象
              data: {
                showData: showData,
                showKey: this.showKey
              }// props
            },
            area: ['1320px', '700px'],
            title: '查看采购检验单', // 标题
            shadeClose: false // 点击遮罩是否关闭
          })
        })
      } else if (row.formTypeName == '生产检验') {
        productionInspectionFormInfo(row[this.mainId]).then(res => {
          if (res.data.resultCode == '' || res.data.resultCode == 'null') {
            res.data.resultCode = ''
          } else if (res.data.resultCode == 0) {
            res.data.resultCode = '通过'
          } else if (res.data.resultCode == 1) {
            res.data.resultCode = '不通过'
          }
          const showData = this.$deepClone(res.data)
          const newlistData = JSON.parse(res.data.titleJson)
          const newlistData1 = JSON.parse(res.data.entityTitleJson)
          const newData = JSON.parse(res.data.qualityJson)
          const newData1 = JSON.parse(res.data.entityQualityJson)
          showData.listData = newlistData
          showData.listData1 = newlistData1
          showData.data = newData
          showData.data1 = newData1
          this.$layer.iframe({// 弹框
            content: {
              content: ShowDetailOld, // 传递的组件对象
              parent: this, // 当前的vue对象
              data: {
                showData: showData,
                showKey: this.showKey1
              }// props
            },
            area: ['1320px', '700px'],
            title: '查看生产检验单', // 标题
            shadeClose: false // 点击遮罩是否关闭
          })
        })
      }
    },
    getUser() {
      userList().then(res => {
        this.userList = res.data.map(item => {
          return { value: item.userId, label: item.realName }
        })
      })
    },
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 1) {
        return 'SaleOrderCodeColumnClass'
      }
      if (!row.isNotselected) {
        return 'displayNoneClass'
      }
    },
    tableSelectable(row, index) {
      if (row.isNotselected) {
        return true
      } else {
        return false
      }
    },
    getList() {
      exportList(this.pageData).then(res => {
        res.data.forEach((item) => { item.isNotselected = true })
        this.tableData = res.data
        this.total = res.total
        this.loading = false
        this.$nextTick(() => {
          this.setSelectRow(this)// 设置行选中
          this.tableHeight = this.$refs.table_container.offsetHeight
        })
      })
    },
    getTypeList() {
      materType().then(res => {
        this.materialTypeList = res.data.map(item => {
          return { value: item.id, label: item.name }
        })
      })
    },
    getExportData(data) {
      data.importIds = this.selectionsAll.map(item => item.onlyId).toString()
      return new Promise(function(resolve, reject) {
        exportList(data).then(res => {
          resolve({ data: res.data })
        })
      })
    },
    getSummaries(param) {
      const {
        columns,
        data
      } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = '合计'
          return
        }
        if (column.property == 'number') {
          const values = data.map(item => item.number)
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      })
      return sums
    }

  }
}
</script>

<style lang="less" scoped>
/deep/.el-tooltip{
  display: flex !important;
}
/deep/ .el-table__fixed-footer-wrapper tr :last-child{
  top: 41px;
}
/deep/ .el-table__footer-wrapper tbody td.el-table__cell{
  background-color: transparent!important;
}
// /deep/ .el-table .el-table__fixed{
//   height: auto !important;
//   bottom: 27px !important;
// }
/deep/ .SaleOrderCodeColumnClass_expand{
  display: inline-block;
  width: 20px;
  line-height: 20px;
  height: 20px;
  text-align: center;
  margin-right: 3px;
}
/deep/.el-table .displayNoneClass .cell .el-checkbox__inner{
  display: none
}
</style>
